package com.cloud.core.aop;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 登陆拦截器
 * Copyright: Copyright (C) 2020 DLANGEL, Inc. All rights reserved.
 * Company: 大连安琪科技有限公司
 *
 * @author dcl
 * @since 2020-07-08 13:37
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // token 校验
        NoAuthCheck authCheck = null;
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            authCheck = method.getAnnotation(NoAuthCheck.class);
        }
        if (authCheck != null) {
            System.out.println("tokenInterceptor aucthcheck true!!");
            return true;
        }
        String authToken = request.getHeader("authToken") == null ? request.getParameter("authToken") : request.getHeader("authToken");

        if (StringUtils.isEmpty(authToken)) {
            // 这里自定义的一个异常，与全局异常捕获配合
            throw new Exception("请先登录");
        } else {
            UserDto userDto = new UserDto();
            userDto.setToken(authToken);
            SubjectContextHolder.setSubject(userDto);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO 自动生成的方法存根

    }

    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        // TODO 自动生成的方法存根

    }
}
